//
// Created by Semir on 2020/5/11.
//

#include <iostream>

using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    explicit ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* connectListNode(int* arr, int length) {
    if (arr == nullptr || length <= 0) {
        return nullptr;
    }
    auto* head = new ListNode(arr[0]);
    auto* node = head;
    for (int i = 1; i < length; i++) {
        node->next = new ListNode(arr[i]);
        node = node->next;
    }
    return head;
}

ListNode* deleteDuplication(ListNode* pHead) {
    if (pHead == nullptr) {
        return nullptr;
    }
    auto* dNode = new ListNode(-99999);
    dNode->next = pHead;
    auto* cNode = dNode->next;
    ListNode* tmpNode = nullptr;
    while (cNode != nullptr && cNode->next != nullptr) {
        if (cNode->next->val == cNode->val) {
            int tmpVal = cNode->val;
            while (cNode->next != nullptr && cNode->next->val == tmpVal) {
                tmpNode = cNode->next;
                cNode->next = tmpNode->next;
                delete tmpNode;
                tmpNode = nullptr;
            }
            if (cNode->next != nullptr) {
                tmpNode = cNode->next;
                cNode->val = tmpNode->val;
                cNode->next = tmpNode->next;
                delete tmpNode;
                tmpNode = nullptr;
                continue;
            } else {
                tmpNode = dNode;
                while (tmpNode->next != nullptr) {
                    if (tmpNode->next == cNode) {
                        tmpNode->next = nullptr;
                        delete  cNode;
                        cNode = nullptr;
                        break;
                    }
                    tmpNode = tmpNode->next;
                }
                break;
            }
        }
        cNode = cNode->next;
    }
    return dNode->next;
}

int main() {
    int arr[7] = {1,2,3,3,4,4,5};
    ListNode* pHead = connectListNode(arr, 7);
    pHead = deleteDuplication(pHead);
    cout << pHead << endl;
    return 0;
}
